package logic

import (
	"context"
	"reflect"

	"googee/common/utils"
	"googee/service/account/rpc/internal/svc"
	"googee/service/account/rpc/types/account"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/sqlc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type DeductAccountLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeductAccountLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeductAccountLogic {
	return &DeductAccountLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

//  减少账户
func (l *DeductAccountLogic) DeductAccount(in *account.IdDeductRequest) (*account.IdResponse, error) {

	resp := &account.IdResponse{}

	configValue := reflect.ValueOf(l.svcCtx.Config.Digital)
	precision := configValue.FieldByName(utils.FirstUpper(in.GetField())).Uint()
	err := l.svcCtx.AccountModel.DeductField(l.ctx, in.Id, in.Field, in.Amount, uint8(precision))

	if err != nil {
		switch err {
		case sqlc.ErrNotFound:
			return nil, status.Error(codes.NotFound, " 账户不存在 ")
		default:
			return nil, err
		}
	}

	accountmodel, err := l.svcCtx.AccountModel.FindOne(l.ctx, in.Id)
	if err == sqlc.ErrNotFound {
		return nil, status.Error(codes.NotFound, " 账户不存在 ")
	}

	copier.Copy(resp, accountmodel)
	return resp, nil

}
